<?php
namespace App\Models;
use Illuminate\Support\Facades\DB;

class ShopGroupGoods extends CommonModel {
	protected $table = 'shop_group_goods';

    // 只查询上架的和正常结束
    public function scopeSales($query){
        $query->whereIn('status',[2,3])->where('start_time','<',date('Y-m-d H:i:s'));
    }
    public function scopeField($query){
        $query->select('shop_group_goods.id','shop_group_goods.goods_name','goods_price','goods_spec', 'goods_image','market_price','stock','all_stock','end_time as time')->orderBy('end_time','desc');
    }
    public function scopeList($query){
        $return=$query->pages();
        return $return;
    }
    //商品详情
    public function getGoodsDetail($goods_id){

        $goods_detail=DB::table('shop_group_goods')->select('id','goods_name','goods_price','store_id','goods_image','goods_spec', 'summary','market_price','stock','all_stock','start_time','end_time as time','status')->where(['id'=>$goods_id])->first();
        $store_detail= ShopStore::getStoreDetailById($goods_detail->store_id);
        $goods_detail->service_id = $store_detail->uid;
        return $goods_detail;
    }
    //检测商品状态
    public function checkGoodsStatus($goods_id,$village_id,$goods_number){
        $data = self::getGoodsDetail($goods_id);
        $check = DB::table('shop_goods_village')->where(['goods_id'=>$goods_id,'village_id'=>$village_id,'goods_type'=>2])->first();
        if(!$check){
            return ['msg'=>'当前小区不支持此商品配送，请切换小区后重试','status'=>0];
        }

        if($data->status!=2){
             return ['msg'=>'商品已下架','status'=>0];
        }
        if($data->start_time >date('Y-m-d H:i:s')){
            return ['msg'=>'活动暂未开始','status'=>0];
        }
        unset($data->time);
        unset($data->start_time);
        unset($data->summary);
        unset($data->all_stock);
        unset($data->stock);
        $return = array();
        $store_detail= ShopStore::getStoreDetailById(1);
        $data->status = 1;
        $data->goods_number = 1;
        $data->goods_type = 2;
        $store_detail->goods_list[] = $data;
        $store_detail->all_number = 1;
        $store_detail->all_price = bcmul($data->goods_price,$goods_number,2); //商品总价

        $return['store_list'][] =$store_detail;
        $return['all_price'] = $store_detail->all_price ;
        $return['goods_all_price'] = $store_detail->goods_all_price ;
        return ['msg'=>'OK','status'=>1,'data'=>$return];
    }
    //下订单增加更新商品库存与销量
    public function updatedGoodsStock($goods_id,$goods_number){
        ShopGoodsStock::addSaleNumber($goods_id,2,$goods_number);
        return self::where(['id'=>$goods_id])->increment('stock',$goods_number);
    }
    //取消订单更新库存与销量
    public function rbackGoodsStock($goods_id,$goods_number){
        ShopGoodsStock::delSaleNumber($goods_id,2,$goods_number);
        return self::where(['id'=>$goods_id])->decrement('stock',$goods_number);
    }
}